import type { MyWaterfallParams, Nullable } from '../type'
import { getItemWidth } from '../utils'

export function useCalculateCols(props: MyWaterfallParams) {
  const wrapperWidth = ref<number>(0)
  const waterfallWrapper = useTemplateRef<Nullable<any>>('waterfallWrapper')

  // const setWidth = useDebounceFn((width: number) => {
  //   wrapperWidth.value = width
  // }, 300)

  useResizeObserver(waterfallWrapper, entries => {
    const entry = entries[0]
    const { width } = entry.contentRect
    // setWidth(width)
    wrapperWidth.value = width
  })

  const colWidth = computed(() => {
    return getItemWidth({
      wrapperWidth: wrapperWidth.value,
      breakpoints: props.breakpoints,
      gutter: props.gutter,
      hasAroundGutter: props.hasAroundGutter,
      initWidth: props.width
    })
  })

  const cols = computed(() => {
    const val = wrapperWidth.value / colWidth.value
    return Math.floor(val)
  })

  const offsetX = computed(() => {
    if (props.align === 'left') {
      return 0
    } else if (props.align === 'center') {
      const offset = props.hasAroundGutter ? props.gutter : -props.gutter
      const contextWidth = cols.value * (colWidth.value + props.gutter) + offset
      return (wrapperWidth.value - contextWidth) / 2
    } else {
      const offset = props.hasAroundGutter ? props.gutter : -props.gutter
      const contextWidth = cols.value * (colWidth.value + props.gutter) + offset
      return wrapperWidth.value - contextWidth
    }
  })

  return {
    waterfallWrapper,
    wrapperWidth,
    colWidth,
    cols,
    offsetX
  }
}
